///\file image.cpp
///\brief contient les implémentations de la classe Image
///\author { V.Allombert, A.Blanchard, A.Carteron, V.Pelletier } 
#include "image.hh"
#include <iostream>
#include <cstdlib>
#include <IL/ilu.h>

bool Image::initialized = false;

Image::Image(const char* name) : i(0){
  if(!initialized){
    ilInit(); 
    iluInit();
    ilOriginFunc(IL_ORIGIN_LOWER_LEFT);
    ilEnable(IL_ORIGIN_SET);
    initialized = true;
  }

  ilGenImages(1, &i); 
  bind();

  if(!ilLoadImage((const ILstring)name)){
    std::cerr<<"Impossible de charger l'image : "<<name<<std::endl;
    std::cerr<<iluErrorString(ilGetError())<<std::endl;
    exit(1);
  }
  ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);

  data = reinterpret_cast<pixel*>(ilGetData());
  h = ilGetInteger(IL_IMAGE_HEIGHT);
  w = ilGetInteger(IL_IMAGE_WIDTH);
}

Image::Image(unsigned int width, unsigned int height) : 
  i(0), w(width), h(height)
{
  if(!initialized){
    ilInit(); 
    iluInit();
    ilOriginFunc(IL_ORIGIN_LOWER_LEFT);
    ilEnable(IL_ORIGIN_SET);
    initialized = true;
  }

  ilGenImages(1, &i); 
  bind();
  ilTexImage( w, h, 1, 4, IL_RGBA, IL_UNSIGNED_BYTE, NULL);
  data = reinterpret_cast<pixel*>(ilGetData());
  h = ilGetInteger(IL_IMAGE_HEIGHT);
  w = ilGetInteger(IL_IMAGE_WIDTH);
}

void Image::load(const char* name){
  if(i){
    bind();
    ilDeleteImages(1, &i);
    i = 0;
  }

  ilGenImages(1, &i); 
  bind();

  if(!ilLoadImage((const ILstring)name)){
    std::cerr<<"Impossible de charger l'image : "<<name<<std::endl;
    std::cerr<<iluErrorString(ilGetError())<<std::endl;
    exit(1);
  }
  ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
  data = reinterpret_cast<pixel*>(ilGetData());
  h = ilGetInteger(IL_IMAGE_HEIGHT);
  w = ilGetInteger(IL_IMAGE_WIDTH);
}

void Image::save(const char* name, bool ow) const{
  if(ow) ilEnable(IL_FILE_OVERWRITE);
  
  bind();
  if(!ilSaveImage(name)){
    std::cerr<<"Impossible de sauver l'image"<<name<<std::endl;
    std::cerr<<iluErrorString(ilGetError())<<std::endl;
    exit(1);
  }
  
  ilDisable(IL_FILE_OVERWRITE);
}
